/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利。
 */

/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利。
 */

/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利。
 */

package com.tbit.main.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.tbit.main.constant.TagStatus;
import com.tbit.main.dao.core.TagDao;
import com.tbit.main.pojo.TagBaseInfo;
import com.tbit.main.service.RedisService;
import com.tbit.main.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 *
 * @author <a href="mailto:zhang.bingrong@tbit.com.cn ">zhangbingrong</a>
 * @since 2024/7/17
 */
@Service
public class TagServiceImpl implements TagService {
    public static final String DISPATCH_CURR_TAG_KEY = "maintainPerformance:dispatch:tag:";

    @Autowired
    RedisService redisService;

    @Resource
    private TagDao tagDao;
    @Override
    public List<TagBaseInfo> list(Integer brandId) {
        return tagDao.selectList(brandId, TagStatus.ENABLED.getValue());
    }

    @Override
    public void cacheTags(Integer machineId, List<TagBaseInfo> tags) {
        if (CollUtil.isEmpty(tags)) {
            return;
        }
        String tagIds = tags.stream()
                .map(TagBaseInfo::getId)
                .collect(Collectors.joining(","));
        redisService.add(DISPATCH_CURR_TAG_KEY + machineId, tagIds, 3, TimeUnit.DAYS);
    }

    @Override
    public List<TagBaseInfo> getTags(Integer machineId) {
        String ids = redisService.get(DISPATCH_CURR_TAG_KEY + machineId);
        if (ids == null) {
            return Collections.emptyList();
        }
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        return tagDao.selectByIds(idList);
    }
}
